package com.pig4cloud.pig.ads.controller.ks;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.ads.service.ks.KsAccesstokenService;
import com.pig4cloud.pig.api.entity.KsAuthCodeResponse;
import com.pig4cloud.pig.api.vo.KsAccesstokenReq;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * @Description 快手授权、回调
 * @Author chengang
 * @Date 2022/3/21
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("ks")
@Inner(value = false)
public class KsCallbackController {

	private final KsAccesstokenService ksAccesstokenService;

	@RequestMapping(value = "/adv/callback")
	public R callback(KsAuthCodeResponse response) {
		String state = response.getState();
		String authCode = response.getAuth_code();
		if(StringUtils.isAnyBlank(state, authCode)) {
			return R.failed("快手授权回调返回结果不合法");
		}

		String stateStr = new String(Base64.getUrlDecoder().decode(state), StandardCharsets.UTF_8);
		Map<String,Object> stateMap = JSON.parseObject(stateStr).getInnerMap();
		Integer userId = (Integer) stateMap.get("userId");
		Integer agentId = (Integer) stateMap.get("agentId");
		ksAccesstokenService.saveAuth(new KsAccesstokenReq().setState(state).setAuthCode(authCode).setUserId(userId).setAgentId(agentId));
		return R.ok(null,"快手授权成功");
	}

}
